/* 
 * Copyright 2012 DevDan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// This service is necessary to keep the broadcastreceivers alive
// A better solution would be to put the receivers to the manifest,
// then no service would be necessary. Unfortunately, 
// this is not possible. If you start the receiver from the manifest, it will not work.

// This way of a service for the broadcast receiver is inspired by the work
// of Jake Basil, thanks!
// Source @ http://code.jakebasile.com/hearing-saver/

package com.devdan.headsetfix;

import static com.devdan.headsetfix.HeadsetCommonConstants.FULL_VERSION;
import static com.devdan.headsetfix.HeadsetCommonConstants.PREFSFILE;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import static com.devdan.headsetfix.HeadsetCommonConstants.*;

public class HeadsetButtonListenService extends Service
{
    private ButtonPressedReceiver receiver;

    @Override
    public IBinder onBind(Intent arg0)
    {
        return null;
    }

	@Override
	public void onCreate()
	{
		super.onCreate();
        // see if there is a saved sticky intent.
        Intent previousIntent = registerReceiver(null, new IntentFilter(
            Intent.ACTION_MEDIA_BUTTON));
        // if there is, tell the receiver to ignore it.
        if(previousIntent != null)
        {
        	ButtonPressedReceiver.getInstance().setIgnoreNext();
        }
        startReceiver();
        
	}
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
    	startReceiver();
        return Service.START_STICKY;
    }

    private void startReceiver() {
        if (isTrialMode()) {
        	showTrialNotification();
        }
        else {
	        SharedPreferences settings = getSharedPreferences(PREFSFILE, 0);       
	    	IntentFilter buttonPressedMediaFilter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);    	
	    	buttonPressedMediaFilter.setPriority(1000000);   	
	    	registerReceiver(ButtonPressedReceiver.getInstance(), buttonPressedMediaFilter);
	    	receiver = ButtonPressedReceiver.getInstance();
	    	receiver.setButtonBehaviour(settings.getInt(BUTTON_BEHAVIOUR, OPTION_REDIAL));
	    	receiver.setPhoneNumber(settings.getString(KEY_CUSTOM_PHONE_NUMBER, NO_NUMBER_GIVEN));
        }
    }
    
    private boolean isTrialMode() {
        boolean functionalityActive;
        if (FULL_VERSION) {
        	functionalityActive = true;
        }
        else {
            TrialChecker trialChecker = new TrialChecker();
            functionalityActive = !trialChecker.isTrialPeriodExceeded(this);
        }        
        return !(functionalityActive);
    }
    
    private void showTrialNotification() {
    	Context context = getApplicationContext();    	
    	String ns = context.NOTIFICATION_SERVICE;
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    	
    	int icon = R.drawable.icon;
//    	CharSequence tickerText = getString( R.string.s_trial_over);
    	CharSequence tickerText = getString(R.string.s_app_expired_title);
    	long when = System.currentTimeMillis();

    	Notification notification = new Notification(icon, tickerText, when);
    	

    	CharSequence contentTitle = getString(R.string.s_app_expired_headline);
    	CharSequence contentText = getString(R.string.s_click_here_to_buy);
    	Intent notificationIntent = new Intent(this, HeadsetfixActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    	mNotificationManager.notify(1, notification);    	
    }
    
    @Override
    public void onDestroy()
    
    {
        super.onDestroy();
        if (receiver != null) {
        	try {
                unregisterReceiver(receiver);
        	}
    		catch(IllegalArgumentException e)
    		{
    			// Exception can be thrown if receiver was already unregistered
    		}        	
        }
    }
    
}
